<template>
  <div class="dept">
    <div class="container">
      <div class="search-card">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
          >{{ $t("system.AddDept") }}</el-button
        >
      </div>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        :expand-row-keys="expandList"
        @expand-change="expandChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          :label="$t('system.DeptName')"
          align="center"
          min-width="260"
        >
          <template #default="{ row }">
            <el-tooltip effect="light" :content="row.deptName" placement="top">
              <div class="deptName">{{ row.deptName }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="userNumber"
          :label="$t('system.DeptHeadcount')"
          align="center"
          min-width="260"
        ></el-table-column>
        <el-table-column
          :label="$t('system.Operate')"
          align="center"
          min-width="260"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.parentId != 0"
              link
              type="primary"
              @click="handleUpdate(row)"
              v-hasPermi="['system:dept:edit']"
              >{{ $t("common.edit") }}</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleAdd(row)"
              v-hasPermi="['system:dept:add']"
              >{{ $t("system.AddSubDept") }}</el-button
            >
            <el-button
              v-if="row.parentId != 0"
              link
              type="primary"
              @click="handleMoveDept(row.deptId, 1)"
              v-hasPermi="['system:dept:moveUp']"
              >{{ $t("system.MoveUp") }}</el-button
            >
            <el-button
              v-if="row.parentId != 0"
              link
              type="primary"
              @click="handleMoveDept(row.deptId, 0)"
              v-hasPermi="['system:dept:moveDown']"
              >{{ $t("system.MoveDown") }}</el-button
            >
            <el-button
              v-if="row.parentId != 0"
              link
              type="danger"
              @click="deletePrompt(row.deptId, row.deptName)"
              v-hasPermi="['system:dept:remove']"
              >{{ $t("common.delete") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改部门对话框 -->
      <el-dialog
        :title="title"
        v-model="open"
        append-to-body
        class="add-dialog"
      >
        <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24" v-if="form.parentId !== 0">
              <el-form-item :label="$t('system.SuperiorDept')" prop="parentId">
                <el-tree-select
                  v-model="form.parentId"
                  :data="deptOptions"
                  :props="{
                    value: 'deptId',
                    label: 'deptName',
                    children: 'children',
                  }"
                  value-key="deptId"
                  placeholder="选择上级部门"
                  check-strictly
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('system.DeptName')" prop="deptName">
                <el-input
                  v-model="form.deptName"
                  placeholder="请输入部门名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="dialogFoot">
          <div class="btn delete" @click="cancel">取消</div>
          <div class="btn search" @click="submitForm">确定</div>
        </div>
      </el-dialog>

      <!-- 删除弹出层 -->
      <el-dialog v-model="deleteVisible" class="no-header-dialog">
        <img src="@/assets/images/warn.png" alt="" />
        <div class="dec">
          删除后不可恢复，确定删除<span class="deletecolor">{{
            deleteName
          }}</span
          >吗？
        </div>
        <div class="chooise">
          <div class="btn delete" @click="closeDelete">取消</div>
          <div class="btn success" @click="deleteApply">确定</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  moveDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import { onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getCurrentInstance } from "vue";

const { $t } = getCurrentInstance().proxy;
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined,
  },
  rules: {
    parentId: [
      { required: true, message: "上级部门不能为空", trigger: "blur" },
    ],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门列表 */
async function getList() {
  loading.value = true;
  try {
    const { data } = await listDept(queryParams.value);
    deptList.value = proxy.handleTree(data, "deptId");
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    // leader: undefined,
    // phone: undefined,
    // email: undefined,
    status: "0",
  };
  proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  listDept().then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  if (row != undefined) {
    form.value.parentId = row.deptId;
  }
  open.value = true;
  title.value = $t("system.AddDept");
}

/**
 * @上下移动部门
 * */
const handleMoveDept = async (deptId, moveType) => {
  try {
    await moveDept({ deptId, moveType });
    getList();
  } catch (error) {
    console.log(error);
    getList();
  }
};

// 展开行的数组
const expandList = ref(["100"]);
/**
 * @展开折叠操作
 * */
function expandChange(row, expanded) {
  if (expanded) expandList.value.push(row.deptId);
  else {
    const index = expandList.value.findIndex((item) => item === row.deptId);
    expandList.value.splice(index, 1);
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log(row);
  reset();
  listDeptExcludeChild(row.deptId).then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = $t("system.EditDept");
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// -------------------------------------------------  删除事件  -----------------------------------------------------

const deleteId = ref();
const deleteName = ref();
const deleteVisible = ref(false);

const deletePrompt = (id, name) => {
  deleteVisible.value = true;
  deleteId.value = id;
  deleteName.value = name;
};

const closeDelete = () => {
  deleteVisible.value = false;
  deleteId.value = null;
  deleteName.value = null;
};

const deleteApply = async () => {
  const res = await delDept(deleteId.value);
  if (res.code === 200) ElMessage.success(res.msg);
  else ElMessage.error(res.msg);
  getList();
  deleteVisible.value = false;
  deleteId.value = null;
  deleteName.value = null;
};
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.deptName + '"的数据项?')
    .then(function () {
      return delDept(row.deptId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss">
.dept {
  .el-table__body-wrapper tbody tr td:nth-child(1) .cell {
    display: flex;
    align-items: center;
    width: 40%;

    transform: translateX(80%);

    .deptName {
      text-align: left;
      white-space: nowrap; /* 防止文本换行 */
      overflow: hidden; /* 隐藏超出部分 */
      text-overflow: ellipsis; /* 显示省略号 */
    }
  }
  .el-button.is-link:not(.is-disabled):focus {
    color: var(--el-button-text-color) !important;
  }
}
</style>

<style lang="scss" scoped>
.dept {
  width: 100%;
  height: 100%;

  .container {
    position: relative;
    width: calc(100% - 40px);
    height: 92%;
    margin: 0 20px 20px;
    border-radius: 10px;
    background: white;
  }

  .search-card {
    position: absolute;
    right: 0px;
    top: -45px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;

    .el-button {
      width: 106px;
      height: 32px;
      opacity: 1;
      border-radius: 4px;
      background: rgba(43, 193, 123, 1);
      border: 1px solid rgba(43, 193, 123, 1);
      font-size: 14px;
      color: white;
    }
  }
}
</style>
